package com.venue.ui.controller;

import java.io.BufferedReader;
import java.io.IOException;

import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.venue.ui.controller.https.HTTP;
import com.venue.ui.controller.request.ReqBase;
import com.venue.ui.util.JsonUtil;

/**
 *
 */
public class BaseController extends Controller {

	protected String getControllerKey() {
		return this.getAttr("ControllerKey");
	}

	protected boolean isPost() {
		return "post".equals(getRequest().getMethod().toLowerCase());
	}

	protected void goBack() {
		goBack(-1);
	}

	protected void goBack(int step) {
		renderJS("history.go(" + step + ")");
	}

	protected void alertAndGoback(String msg) {
		alertAndGoback(msg, -1);
	}

	protected void alertAndGoback(String msg, int step) {
		renderJS("alert('" + msg + "');history.go(" + step + ")");
	}

	protected void renderJS(String jsContent) {
		renderHtml("<script type=\"text/javascript\">" + jsContent
				+ "</script>");
	}

	/**
	 * 获取请求数据
	 * 
	 * @param valueType
	 * @return
	 */
	protected <T> T getRequestObject(Class<T> valueType) {
		StringBuilder json = new StringBuilder(1024);
		BufferedReader reader = null;
		try {

			reader = this.getRequest().getReader();
			String line = null;
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}

		} catch (Exception e) {
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return JsonUtil.fromJson(json.toString(), valueType);
	}

	public <T> T post(ReqBase req, HTTP http, Class<T> valueType) {
		String data = JsonUtil.toJson(req);
		String ip = PropKit.get("ip");
		String rsp = HttpKit.post(ip + http.getUrl(), data);
		return JsonUtil.fromJson(rsp, valueType);
	}
}
